package cn.com.haopy.dataes.core.utils;

import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.openssl.jcajce.JcaPKCS8Generator;
import org.bouncycastle.util.io.pem.PemObject;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class RSAUtil {
    private static final String KEY_ALGORITHM = "RSA";
    private static final int KEY_SIZE = 1024;
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";

    private static final int MAX_ENCRYPT_BLOCK = 53;
    private static final int MAX_DECRYPT_BLOCK = 64;

    public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);

        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        Map<String, Object> keyMap = new HashMap<>(2);
        keyMap.put(PRIVATE_KEY, privateKey);
        keyMap.put(PUBLIC_KEY, publicKey);

        return keyMap;
    }

    /***********************获取私钥**********************/
    public static byte[] getPrivateKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PRIVATE_KEY);

        return key.getEncoded();
    }

    public static String getPrivateKeyString(Map<String, Object> keyMap) {
        byte[] key = getPrivateKey(keyMap);

        return Base64.getEncoder().encodeToString(key);
    }

    public static PrivateKey getPrivateKey(byte[] key) throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        return keyFactory.generatePrivate(keySpec);
    }

    public static PrivateKey getPrivateKey(String key) throws Exception {
        key = key.replace("\n", "").replace("\r", "");

        return getPrivateKey(Base64.getDecoder().decode(key));
    }

    public static String getPrivateKeyString(byte[] key) throws Exception {
        return Base64.getEncoder().encodeToString(key);
    }

    public static String getPrivateKeyPemString(String key) throws Exception {
        PrivateKey privateKey = getPrivateKey(key);

        JcaPKCS8Generator jcaPKCS8Generator = new JcaPKCS8Generator(privateKey, null);
        PemObject obj1 = jcaPKCS8Generator.generate();
        StringWriter sw1 = new StringWriter();
        try (JcaPEMWriter pw = new JcaPEMWriter(sw1)) {
            pw.writeObject(obj1);
        }

        return sw1.toString();
    }

    public static String getPrivateKeyPemString(byte[] key) throws Exception {
        return getPrivateKeyPemString(getPrivateKeyString(key));
    }

    public static String getPrivateKeyPemString(Map<String, Object> keyMap) throws Exception{
        return getPrivateKeyPemString(getPrivateKeyString(keyMap));
    }

    /***********************获取公钥**********************/
    public static byte[] getPublicKey(Map<String, Object> keyMap) {
        Key key = (Key) keyMap.get(PUBLIC_KEY);

        return key.getEncoded();
    }

    public static String getPublicKeyString(Map<String, Object> keyMap) {
        byte[] key = getPublicKey(keyMap);

        return Base64.getEncoder().encodeToString(key);
    }

    public static PublicKey getPublicKey(byte[] key) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);

        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        return keyFactory.generatePublic(x509EncodedKeySpec);
    }

    public static PublicKey getPublicKey(String key) throws Exception {
        key = key.replace("\n", "").replace("\r", "");

        return getPublicKey(Base64.getDecoder().decode(key));
    }

    public static String getPublicKeyString(byte[] key) throws Exception {
        return Base64.getEncoder().encodeToString(key);
    }

    public static String getPublicKeyPemString(String key) throws Exception {
        PublicKey publicKey = getPublicKey(key);

        return "";
    }

    public static String getPublicKeyPemString(byte[] key) throws Exception {
        return getPublicKeyPemString(getPublicKeyString(key));
    }

    public static String getPublicKeyPemString(Map<String, Object> keyMap) throws Exception {
        return getPublicKeyPemString(getPublicKeyString(keyMap));
    }

    /***********************加密**********************/
    public static byte[] encryptByPrivateKey(byte[] key, byte[] data) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);

        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        return encryptByKey(data, privateKey, keyFactory.getAlgorithm());
    }

    public static String encryptByPrivateKey(String key, String data) throws Exception {
        data = data.replace("\n", "").replace("\r", "");
        byte[] encryptedData = encryptByPrivateKey(Base64.getDecoder().decode(key), data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }


    public static byte[] encryptByPublicKey(byte[] key, byte[] data) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);

        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        return encryptByKey(data, publicKey, keyFactory.getAlgorithm());
    }

    public static String encryptByPublicKey(String key, String data) throws Exception {
        data = data.replace("\n", "").replace("\r", "");
        byte[] encryptedData = encryptByPublicKey(Base64.getDecoder().decode(key), data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedData);
    }


    private static byte[] encryptByKey(byte[] data, Key key, String algorithm) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        return getCipherFinalData(data, cipher, MAX_ENCRYPT_BLOCK);
    }

    /***********************解密**********************/
    public static byte[] decryptByPrivateKey(byte[] key, byte[] encryptedData) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

        return decryptByKey(encryptedData, privateKey, keyFactory.getAlgorithm());
    }

    public static String decryptByPrivateKey(String key, String encryptedData) throws Exception {
        encryptedData = encryptedData.replace("\n", "").replace("\r", "");
        byte[] decryptedData = decryptByPrivateKey(Base64.getDecoder().decode(key), encryptedData.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(decryptedData);
    }


    public static byte[] decryptByPublicKey(byte[] key, byte[] encryptedData) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        return decryptByKey(encryptedData, publicKey, keyFactory.getAlgorithm());
    }

    public static String decryptByPublicKey(String key, String encryptedData) throws Exception {
        encryptedData = encryptedData.replace("\n", "").replace("\r", "");
        byte[] decryptedData = decryptByPublicKey(Base64.getDecoder().decode(key), encryptedData.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(decryptedData);
    }


    private static byte[] decryptByKey(byte[] data, Key key, String algorithm) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key);

        return getCipherFinalData(data, cipher, MAX_DECRYPT_BLOCK);
    }

    /***********************私钥签名**********************/
    public static byte[] signByPrivateKey(byte[] key, byte[] data) throws Exception {
        PrivateKey privateKey = getPrivateKey(key);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initSign(privateKey);
        sig.update(data);

        return sig.sign();
    }
    public static byte[] signByPrivateKey(byte[] key, String data) throws Exception {
        return signByPrivateKey(key, data.getBytes(StandardCharsets.UTF_8));
    }
    public static byte[] signByPrivateKey(String key, byte[] data) throws Exception {
        key = key.replace("\n", "").replace("\r", "");
        return signByPrivateKey(Base64.getDecoder().decode(key), data);
    }
    public static byte[] signByPrivateKey(String key, String data) throws Exception {
        return signByPrivateKey(key, data.getBytes(StandardCharsets.UTF_8));
    }

    public static String signStringByPrivateKey(byte[] key, byte[] data) throws Exception {
        return Base64.getEncoder().encodeToString(signByPrivateKey(key, data));
    }
    public static String signStringByPrivateKey(byte[] key, String data) throws Exception {
        return Base64.getEncoder().encodeToString(signByPrivateKey(key, data));
    }
    public static String signStringByPrivateKey(String key, byte[] data) throws Exception {
        return Base64.getEncoder().encodeToString(signByPrivateKey(key, data));
    }
    public static String signStringByPrivateKey(String key, String data) throws Exception {
        return Base64.getEncoder().encodeToString(signByPrivateKey(key, data));
    }

    /***********************公钥验签**********************/
    public static boolean verifyByPublicKey(byte[] data, byte[] sign, byte[] key) throws Exception {
        PublicKey publicKey = getPublicKey(key);
        Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
        sig.initVerify(publicKey);
        sig.update(data);

        return sig.verify(sign);
    }
    public static boolean verifyByPublicKey(String data, byte[] sign, byte[] key) throws Exception {
        return verifyByPublicKey(data.getBytes(StandardCharsets.UTF_8), sign, key);
    }
    public static boolean verifyByPublicKey(byte[] data, String sign, byte[] key) throws Exception {
        return verifyByPublicKey(data, Base64.getDecoder().decode(sign), key);
    }
    public static boolean verifyByPublicKey(String data, String sign, byte[] key) throws Exception {
        return verifyByPublicKey(data.getBytes(StandardCharsets.UTF_8), Base64.getDecoder().decode(sign), key);
    }
    public static boolean verifyByPublicKey(byte[] data, byte[] sign, String key) throws Exception {
        return verifyByPublicKey(data, sign, Base64.getDecoder().decode(key));
    }
    public static boolean verifyByPublicKey(String data, byte[] sign, String key) throws Exception {
        return verifyByPublicKey(data.getBytes(StandardCharsets.UTF_8), sign, Base64.getDecoder().decode(key));
    }
    public static boolean verifyByPublicKey(byte[] data, String sign, String key) throws Exception {
        return verifyByPublicKey(data, Base64.getDecoder().decode(sign), Base64.getDecoder().decode(key));
    }
    public static boolean verifyByPublicKey(String data, String sign, String key) throws Exception {
        return verifyByPublicKey(data.getBytes(StandardCharsets.UTF_8), Base64.getDecoder().decode(sign), Base64.getDecoder().decode(key));
    }

    private static byte[] getCipherFinalData(byte[] data, Cipher initedCipher, int maxBlock) throws Exception {
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int offset = 0;
        byte[] cache;

        int i = 0;
        while (inputLen - offset > 0) {
            if (inputLen - offset > maxBlock) {
                cache = initedCipher.doFinal(data, offset, maxBlock);
            } else {
                cache = initedCipher.doFinal(data, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * maxBlock;
        }

        byte[] encryptedData = out.toByteArray();
        out.close();

        return encryptedData;
    }




}
